import { defineStore } from 'pinia'
import router from "@/router/index";
import {setTokenTime} from '@/util/auth'
import { LoginApi,GetUserInfoApi } from "@/util/request"
// 第一个参数是store的唯一ID，第二个参数是一个函数，返回store的配置对象
export const useLoginStore = defineStore('app', {
    // 类似于Vuex中的state，存储数据
    state: () => {
        return {
            token: localStorage.getItem('token') || '',
            userInfo : {nickname:''}
        };
    },
    getters: {
        getToken: (state) => {
          return state.token;
        },
        getUserInfo:(state)=>{
            return state.userInfo;
        }
      },
    // 类似于Vuex中的actions和mutations的组合，用于修改state
    actions: {
        setToken(token) {
            this.token = token;
            console.log('设置token')
            localStorage.setItem('token',token)
            //设置登录的时间
            setTokenTime()
        },
        Login(loginData) {   
            return new Promise((resolve, reject) => {
                LoginApi(loginData)
                    .then((data) => {
                        const { tokenType, accessToken, refreshToken } = data;
                        this.setToken(tokenType + " " + accessToken);
                        resolve();
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        Logout() {   
            this.setToken('')
            localStorage.clear()
            this.userInfo={nickname:''};
            console.log('到登录')
            router.replace('/login')
        },
        LoadUserInfo(){
            GetUserInfoApi().then((data)=>{
                this.userInfo=data;
                console.log(data)
            }).catch((error)=>{
                console.log(error)
            });
        }
    }
});

